package com.zlp.mall.portal.controller;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zlp.mall.common.api.R;
import com.zlp.mall.common.exception.ApiException;
import com.zlp.mall.portal.modules.oms.service.OrderService;
import com.zlp.mall.portal.modules.oms.service.PayService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/pay")
@Api(value = "PayController",tags = "支付模块")
public class PayController {

    @Resource
    private PayService payService;
    @Resource
    private OrderService orderService;

    /**
     * 生成当面付二维码
     */
    @PostMapping(value="tradeQrCode")
    @ApiOperation(value = "支付接口，只实现支付宝支付，微信支付暂未实现")
    public R tradeQrCode(
            @RequestParam("orderId") @ApiParam(name = "orderId",value = "订单id",required = true) Long orderId,
            @RequestParam("payType") @ApiParam(name = "payType",value = "支付类型(1:支付宝2：微信)",allowableValues = "1,2",required = true) Integer payType
    ){
        if(payType>2 || payType<0){
            throw  new ApiException("支付类型参数错误！");
        }
        return payService.tradeQrCode(orderId,payType);
    }

    @PostMapping(value="/paySuccess/{payType}")
    public void getMyOrders(@PathVariable("payType") Integer payType,
            HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            if(!name.toLowerCase().equals("sign_type")) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
        }

        String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwUpyecFNQ+yaW2jWzQA71LEcT1xk62vOpNukZFOWCDTKxL2WY6OVv4uh2RajKFdslHfWjvwooXr5TsKtvnv0iRLDjbsuh6H6va5jWa4w2FPOqSGybQzDBSAAx2bAWsjdP/wtHxISyI0JTsxCstjHYippkbvZsa4cDCn3a/7NQuIwrxwlzI3F5AVitENJcRBWDZlbbu1HKp3Af9MDRCj91nNlZrnJZ27CWzPiNhoW5wvo9a1I2+qUQoBvyKYxY0mPeBnSngaYTNXN8RU1MiTwQ6sri2TblSV8EXR+4org82NgjWdWM4L7Bsnz/bA2OTP7jMC1EePnAcsdvUwQPnbQtwIDAQAB";

        // 验签  ：去除sign和sign_type 参数 进行验签， checkV1 会在方法中去除，CheckV2不会去除sign_type，所以要手动排除
        boolean signVerified = AlipaySignature.rsaCheckV2(params, alipay_public_key, "utf-8","RSA2"); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            // 订单id
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            if(StrUtil.isNotBlank(out_trade_no) && NumberUtil.isNumber(out_trade_no)){
                Long orderId=Long.parseLong(out_trade_no);
                orderService.paySuccess(orderId,payType);
                log.info("支付成功");
            }
        }else {
            System.out.println("验签失败");
        }


    }




}

